package com.util;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class StringUtils {
	
	private StringUtils(){
		
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(charNum("sdhsidi21382918392sdsaid傻傻的").get("中文字符"));
	    System.out.println(splitStrBylength("s我adas你说的是sada",3));
	}
	
	public static String splitStrBylength(String str,int splitLength) throws Exception {
	    byte[] bt = str.getBytes("GBK");//GBK编码，汉字占两个字节，UTF-8占三个
	    int wordLength = 0;
	    int chineseLength = 0;
	    int count = 0;
	    if(bt.length > splitLength) {
	        for (int i = 0; i < splitLength; i++) {
                if(bt[i] < 0 && ++ count > 0 && count%2 == 0) { //汉字的字节数小于0
                    chineseLength ++;
                }else {
                    wordLength ++;
                }
            }
	        return str.substring(0,wordLength + chineseLength);
	    }else {
	        return "截取数超过字符长度";
	    }
	}
	
	/**
	 * 找出字符串中的各种字符
	 * @param str
	 * @return  
	 * @author wujw
	 */
	public static Map<String,Integer> charNum(String str){
		int chineseCount = 0;
		int englishCount = 0;
		int digitCount = 0;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if(c >= '0' && c <= '9') {
				digitCount ++;
			}else if((c >= 'a' && c <= 'z') && (c >= 'A' && c <= 'Z')) {
				englishCount ++;
			}else{
				chineseCount ++;
			}
		}
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("中文字符", chineseCount);
		map.put("英文字符", englishCount);
		map.put("数字字符", digitCount);
		
		return map;
	}


	/**
	 * 处理0,1组合的字符串，常见于标记，自定义的组合，例如：0000000代表一个星期中的星期几，如果1010101则代表1,3,5,7
	 * @param bitString   需要处理的字符串
	 * @return  将111000111解析成1-3,7-9
	 */
	public static String conVertBitToString(String bitString) {
		String res = "";
		bitString = "0" + bitString + "0";
		int cur = 0;
		while (bitString.indexOf("01", cur) != -1) {
			int startIndex = bitString.indexOf("01", cur) + 1;
			int endIndex = bitString.indexOf("10", cur);
			if (startIndex == endIndex) {
				res += startIndex + ",";
			} else {
				res += startIndex + "-" + endIndex + ",";
			}
			cur = endIndex + 1;
		}
		//去除最后一个逗号
		if(res.lastIndexOf(",")>0){
			res = res.substring(0, res.lastIndexOf(","));
		}
		return res;
	}


	/**
	 * 获取指定长度的系统流水号
	 * @param length  指定的长度
	 * @param isNumber 是否是纯数字要求
	 * @return uuid   返回的结果
	 */
	public static String getSysJournalNo(int length,boolean isNumber){
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		if(uuid.length() > length){
			uuid = uuid.substring(0,length);
		}else if(uuid.length() < length){
			for (int i = 0; i < length - uuid.length(); i++) {
				uuid = uuid + Math.round(Math.random()*9);
			}
		}
		if(isNumber){
			return uuid.replaceAll("a", "1").replaceAll("b", "2").replaceAll("c", "3").replaceAll("d", "4").replaceAll("e", "5").replaceAll("f", "6");
		}else{
			return uuid;
		}
	}
}
